<?php
namespace app\know\validate;

use app\know\model\QuestionContentModel;
use app\know\model\QuestionModel;
use think\Validate;
use think\facade\Log;

class QuestionContentValidate extends Validate
{
    protected $rule = [
        'content' => 'require|min:1|checkContent|checkContentRepeat',
        'id' => 'require|gt:0',
    ];

    protected $message = [
        'content.require' => '试题内容为必填项',
        'content.min' => '试题内容不能为空',
        'id.require' => 'id不能为空',
    ];

    protected $scene = [
        'add'  => ['content'],
        'edit' => ['id', 'content'],
        'delete' => ['id'],
        'addChild' => ['content'],
    ];

    protected function checkContentRepeat($value, $rule, $data)
    {
        if ($this->currentScene != 'edit') 
        {
            return true;
        }

        $model = new QuestionContentModel();
        $item  = $model->where('id', '<>', $data['id'])
                        ->where('content', $data['content'])
                        ->find();

        if (empty($item)) 
        {
            return true;
        } 
        else 
        {
            return "---编辑：试题内容已经存在---" . $item['id'];
        }
    }

    protected function checkContent($value, $rule, $data)
    {
        if ($this->currentScene != 'add') 
        {
            return true;
        }

        $model = new QuestionContentModel();
        $item  = $model->where('content', $data['content'])->find();

        if (empty($item)) 
        {
            return true;
        } 

        $qitem = QuestionModel::where('uuid', $item['question_uuid'])->find();
        if ($qitem['is_delete'] === 0)
        {
            return "---添加：试题内容已经存在---" . $item['id'];
        }
    }
}